package br.com.relatorios.dao;

import java.util.List;

import javax.persistence.*;
import javax.xml.bind.ValidationException;



/**
 *
 * @author Juliano
 */
public abstract class BaseDAO<E> {
	
	EntityManagerFactory emf = Persistence.createEntityManagerFactory("HibernateJPAPU");
	protected EntityManager entityManager = emf.createEntityManager();

	public void insert(E e) {
		EntityTransaction transaction = entityManager.getTransaction();
		transaction.begin();
		entityManager.persist(e);
        transaction.commit();
	}

	public E update(E e) {
		EntityTransaction transaction = entityManager.getTransaction();
		transaction.begin();
		e = entityManager.merge(e);
        transaction.commit();
		return e;
	}

	public E load(Class <E> c , Long pk) {
		return entityManager.find(c, pk);
	}
	
	public void delete(E e) throws ValidationException  {
		try {
			EntityTransaction transaction = entityManager.getTransaction();
			transaction.begin();
			entityManager.remove(e);
	        transaction.commit();
		} catch (PersistenceException ex) {
			throw new ValidationException(ex.getMessage());
		}
	} 
	

	@SuppressWarnings("unchecked")
	public List listaTodos(Class classe){
		Query query =entityManager.createQuery("from "+classe.getName());
		return query.getResultList();
	}
}